package vip.ola.manage.sys.ctrl;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import vip.ola.core.common.annotation.MethodLog;
import vip.ola.core.common.constant.MchConstant;
import vip.ola.core.common.constant.RetEnum;
import vip.ola.core.common.domain.BizResponse;
import vip.ola.core.common.domain.PayResponse;
import vip.ola.core.common.util.GoogleAuthenticator;
import vip.ola.core.entity.AgentInfo;
import vip.ola.core.entity.SysUser;
import vip.ola.manage.common.ctrl.BaseController;
import vip.ola.manage.common.service.RpcCommonService;

import javax.servlet.http.HttpServletRequest;

import static vip.ola.core.common.constant.Constant.*;

/**
 * 代理商安全中心
 */
@Controller
@RequestMapping(MGR_CONTROLLER_ROOT_PATH + "/security")
public class SecurityCenterController extends BaseController {

    @Autowired
    private RpcCommonService rpcCommonService;

    /**
     * 得到用户谷歌验证二维码
     *
     * @return
     */
    @RequestMapping("/google_qrcode")
    @ResponseBody
    public ResponseEntity<?> getGoogleAuthQrCode() {
        SysUser sysUser = rpcCommonService.rpcSysService.findByUserId(getUser().getId());
        String googleAuthSecretKey = sysUser.getGoogleAuthSecretKey();
        if (StringUtils.isBlank(googleAuthSecretKey)) {
            googleAuthSecretKey = GoogleAuthenticator.generateSecretKey();
            SysUser updateUser = new SysUser();
            updateUser.setUserId(sysUser.getUserId());
            updateUser.setGoogleAuthSecretKey(googleAuthSecretKey);
            int count = rpcCommonService.rpcSysService.update(updateUser);
            if (count != 1) return ResponseEntity.ok(PayResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
        }
        String qrcode = GoogleAuthenticator.getQRBarcode( "manage(" + sysUser.getNickName() + ")", googleAuthSecretKey);
        String qrcodeUrl = mainConfig.getPayUrl() + "/qrcode_img_get?url=" + qrcode + "&widht=200&height=200";
        return ResponseEntity.ok(PayResponse.buildSuccess(qrcodeUrl));
    }

    /**
     * 绑定谷歌验证
     *
     * @return
     */
    @RequestMapping("/google_bind")
    @ResponseBody
    public ResponseEntity<?> bindGoogleAuth(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        // 获取传的验证码
        Long code = getLongRequired(param, "code");
        if (!checkGoogleCode(getUser().getId(), code)){
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_GOOGLECODE_NOT_MATCH));
        }
        // 修改数据中绑定状态
        SysUser updateUser = new SysUser();
        updateUser.setUserId(getUser().getId());
        updateUser.setGoogleAuthStatus(MchConstant.PUB_YES);
        int count = rpcCommonService.rpcSysService.update(updateUser);
        if (count != 1) return ResponseEntity.ok(PayResponse.build(RetEnum.RET_MCH_GOOGLEAUTH_SECRETKEY_BIND_FAIL));
        return ResponseEntity.ok(PayResponse.buildSuccess());
    }

    /**
     * 设置登录验证方式
     *
     * @return
     */
    @RequestMapping("/login_set")
    @ResponseBody
    @MethodLog(remark = "设置登录验证方式")
    public ResponseEntity<?> setLogin(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Byte loginSecurityType = getByteRequired(param, "loginSecurityType");
        Long code = getLongRequired(param, "code");
        if (!checkGoogleCode(getUser().getId(), code)){
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_GOOGLECODE_NOT_MATCH));
        }
        if (loginSecurityType == 1) {    // 登录密码+谷歌验证组合
            SysUser sysUser = rpcCommonService.rpcSysService.findByUserId(getUser().getId());
            if (sysUser.getGoogleAuthStatus() != MchConstant.PUB_YES) {
                // 没有绑定谷歌
                return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_GOOGLEAUTH_NOT_BIND));
            }
        }
        SysUser updateUser = new SysUser();
        updateUser.setUserId(getUser().getId());
        updateUser.setLoginSecurityType(loginSecurityType);
        int count = rpcCommonService.rpcSysService.update(updateUser);
        if (count != 1) return ResponseEntity.ok(PayResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
        return ResponseEntity.ok(PayResponse.buildSuccess());
    }

    /**
     * 验证谷歌验证码
     *
     * @param agentId
     * @param code
     * @return
     */
    boolean checkGoogleCode(Long userId, Long code) {
        SysUser sysUser = rpcCommonService.rpcSysService.findByUserId(userId);
        String googleAuthSecretKey = sysUser.getGoogleAuthSecretKey();
        return checkGoogleCode(googleAuthSecretKey, code);
    }

}